package com.crazy.common.el;

import org.springframework.util.StringUtils;

/**
 * 自定义EL函数
 * 
 * @author admin
 */
public abstract class ELFunctions extends StringUtils {
	static final String script = "<(?i)script[^>]*?>.*?</(?i)script>";
	static final String style = "<(?i)style[^>]*?>.*?</(?i)style>";
	static final String comment = "<!--(.|[\r\n])*?-->";
	static final String marker = "<[^>]*>";
	static final String space = "\\s*|\t|\r|\n";

	/**
	 * @param html
	 *            html内容
	 * @return 将html内容转换成纯文本
	 */
	public static String html2text(String html) {
		if (hasText(html)) {
			html = html.replaceAll(script, "");
			html = html.replaceAll(style, "");
			html = html.replaceAll(comment, "");
			html = html.replaceAll(marker, "");
			html = html.replaceAll(space, "");
			return html;
		}
		return "";
	}

	/**
	 * @param text
	 *            文本内容
	 * @param length
	 *            截取字符串长度
	 * @return 将文本内容按指定长度截取，并追加省略号“...”
	 */
	public static String shortText(String text, int length) {
		if (hasText(text)) {
			if (text.length() <= length || length <= 0) {
				return text;
			}
			if (text.length() > length) {
				text = text.substring(0, length);
				text = text.concat("...");
				return text;
			}
		}
		return "";
	}

	/**
	 * @param html
	 *            html内容
	 * @param length
	 *            截取字符串长度
	 * @return 将html内容转换成纯文本,再将文本内容按指定长度截取,并追加省略号“...”.
	 */
	public static String html2textAndShortText(String html, int length) {
		html = html2text(html);
		html = shortText(html, length);
		return html;
	}
}
